<script setup>
import _ from 'lodash'
import animejs from 'animejs';
import {getAnimePlain, isMultipleNode} from '../../../utils/mutil';
import {onMounted, reactive, toRef, toRefs, watch} from "vue";
import {DFT_ICONS} from "@jzl/icons";

const ANIME_TRANSFORMS = [{
  prop: 'translateX',
  value: 50,
  mini: 25
}, {
  prop: 'translateY',
  value: 50,
  mini: 25
}, {
  prop: 'rotate',
  value: 90
}, {
  prop: 'rotateX',
  value: 90
}, {
  prop: 'rotateY',
  value: 90
}, {
  prop: 'opacity',
  value: 0.5
}, {
  prop: 'scale',
  value: 2
}, {
  prop: 'scaleX',
  value: 2
}, {
  prop: 'scaleY',
  value: 2
}, {
  prop: 'skew',
  value: 20
}, {
  prop: 'skewY',
  value: 20
}, {
  prop: 'backgroundColor',
  value: '#F00'
}];
const ANIME_PROPS = [{
  prop: 'color',
  value: '#0F0'
}, {
  prop: 'borderRadius',
  value: '50%'
}, {
  prop: 'borderWidth',
  value: '5px'
}, {
  prop: 'borderColor',
  value: '#FF0'
}, {
  prop: 'width',
  value: '50px',
  mini: "20px"
}, {
  prop: 'height',
  value: '50px',
  mini: '25px'
}, {
  prop: 'left',
  value: '50px',
  mini: '25px'
}, {
  prop: 'top',
  value: '50px',
  mini: '25px'
}, {
  prop: 'right',
  value: '50px',
  mini: '25px'
}, {
  prop: 'bottom',
  value: '50px',
  mini: '25px'
}, {
  prop: 'marginLeft',
  value: '50px',
  mini: '25px'
}, {
  prop: 'marginTop',
  value: '50px',
  mini: '25px'
}, {
  prop: 'marginRight',
  value: '50px',
  mini: '25px'
}, {
  prop: 'marginBottom',
  value: '50px',
  mini: '25px'
}];

const modelValue = defineModel()

const props = defineProps({
  eleDef: {
    type: Object
  },
  currentItemElCode: String
})

const {
  anime,
  propWin,
  animeProps,
  xprops
} = toRefs(reactive({
  anime: null,
  propWin: false,
  animeProps: ANIME_PROPS,
  xprops: []
}))

const willReceiveProps = (newVal) => {
  if (!newVal || !$utils.deepEquals(newVal, anime.value)) {
    init();
  } else {
    // console.log('一样 ... ');
  }
}

const init = async () => {
  anime.value = _.merge({}, getAnimePlain(), modelValue.value);
}

const handlePlayAnime = () => {

  let code = _.get(props.eleDef, "_code");
  let $eles = document.querySelectorAll(`.ele-design-body [j-name=${code}]`);
  let isMultiple = isMultipleNode(props.eleDef);

  _.each($eles, ($el, index) => {
    runAnime($el, isMultiple, index)
  })
}

/*// 获取原 style 样式
const saveOriginalStyle = (el) => {
  const original = {}

  // 遍历 style 对象中所有属性
  for (let prop of el.style) {
    original[prop] = el.style[prop]
  }

  return original
}

// 重置 style 样式
function restoreOriginalStyle(el, originalStyle) {
  // 清空内联样式
  el.style.cssText = ''

  // 重新赋值原始样式
  for (let prop in originalStyle) {
    el.style[prop] = originalStyle[prop]
  }
}*/

const runAnime = async ($el, isMultiple, index) => {
  if(!$el) return;

  let existAniInstance = $el._animeInstance;
  if(existAniInstance?.reset) {
    await existAniInstance.pause();
    await existAniInstance.reset();

    delete $el._animeInstance
  }

  let origStyle = _.cloneDeep($el.style);
  let opts = _.assign({}, getAnimePlain(), anime.value, {
    autoplay: false,
    targets: $el,
    complete: (xxx) => {
      $anime && $anime.reset()
      /*
      if ($el.style) {
        for(let ep in $el.style) {
          if($el.style[ ep ] && !origStyle[ ep ]) delete $el.style[ ep ];
        }
        for (let p in origStyle) {
          $el.style[p] = origStyle[p] || "";
        }
        if (opts.isAutoHeight) {
          $el.style.height = 'auto';
        }
      }*/
    }
  });

  if (opts.loop !== true && !_.isNumber(opts.loop)) delete opts.loop;

  let delay = _.get(opts, "delay") || 0;  // 兼容 direction: "reverse" 情况下 delay 不生效，手动设置

  delete opts.delay;

  if (opts.stagger && delay > 0 && isMultiple && index >= 0) {
    delay = index * delay;
  }

  // 兼容无法处理的情况
  if (opts.height === 'auto') {
    const contentHeight = $el.scrollHeight;

    opts.isAutoHeight = true;
    opts.height = `${contentHeight}px`;
    if ($el.style) {
      origStyle["overflow"] = $el.style.overflow || null;
      origStyle["height"] = $el.style.height || null;

      $el.style.height = '0px';
      $el.style.overflow = "hidden";
    }
  }

  let $anime = animejs(opts);

  $el._animeInstance = $anime;

  if ($el.style) $el.style.visibility = 'hidden';
  setTimeout(() => {
    if ($el.style) $el.style.visibility = 'unset';
    $anime && $anime.play();
  }, delay);
}

const handleShowPropWin = () => {
  propWin.value = true;
}

const getAnimeCfg = (cfg, isMini = false) => {
  let value = cfg.value;
  if (isMini && _.has(cfg, "mini")) {
    value = _.get(cfg, "mini");
  }

  return _.assign({loop: true, duration: 2000}, {[cfg.prop]: value});
}

const getAnimeCfgByProp = (propName, isMini = false) => {
  let cfg = _.find(ANIME_TRANSFORMS, {prop: propName}) || _.find(ANIME_PROPS, {prop: propName});

  return getAnimeCfg(cfg, isMini);
}

const handleSelectAnime = (cfg) => {
  let prop = _.get(cfg, "prop");
  let value = _.get(cfg, "value");

  if (!prop) return;

  if (_.hasIn(anime.value, prop)) {
    return $jui.toast("动画属性已添加，请去修改，勿重复添加！")
  }

  // this.$set(this.anime, prop, value);
  anime.value[prop] = value;
  propWin.value = false;
}

const handleRemoveAnime = (prop) => {
  anime.value[prop] = undefined;
  // this.$set(this.anime, prop, undefined);
  delete anime.value[prop];
}


watch(() => modelValue.value, (newVal, oldVal) => {
  willReceiveProps(newVal, oldVal)
}, {deep: true})

watch(() => anime.value, (animeInfo) => {
  let xps = [];
  for (let p in animeInfo) {
    if (_.find(ANIME_TRANSFORMS, {prop: p}) || _.find(ANIME_PROPS, {prop: p})) {
      xps.push(p);
    }
  }

  xprops.value = xps;
  modelValue.value = animeInfo;
  // this.$emit('change', animeInfo)
}, {deep: true})

watch(() => props.currentItemElCode, () => {
  // console.log(`=====> anime.vue change init ...`)
  init()
})
</script>

<template>
  <div class="ele-prop-item">
    <el-form
      label-width="60px"
      label-position="top"
      size="mini"
      v-if="anime"
    >
      <el-form-item label="">
        <div style="display: flex;justify-content: space-between;align-items: center;min-height: 28px;">
          <el-switch v-model="anime.enable"></el-switch>
          <el-button
            v-if="anime.enable"
            size="small"
            @click="handlePlayAnime"
            plain
            round
            type="primary"
            class="ml-5"
          ><template #icon>
            <JIcon :icon="DFT_ICONS.video" />
          </template> 播放预览
          </el-button>
        </div>
      </el-form-item>
      <template v-if="anime.enable">
        <el-form-item label="播放时机">
          <el-radio-group v-model="anime.play">
            <el-radio label="auto">立即播放</el-radio>
            <el-radio label="view">可视后播放</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="持续时间">
          <template #label>
            <div class="w-full flex justify-between">
              <span>持续时间</span>
              <el-input-number
                v-model="anime.duration"
                size="small"
                :min="0"
                :max="5000"
                class="pure-lack w-20"
                controls-position="right"
              />
            </div>
          </template>
          <el-slider
            v-model="anime.duration"
            class="pl-4 pr-3"
            height="20"
            size="small"
            :min="0"
            :max="5000"
          />
        </el-form-item>
        <el-form-item label="逐个延迟" v-if="isMultipleNode(eleDef)">
          <el-switch v-model="anime.stagger"></el-switch>
        </el-form-item>
        <el-form-item label="延迟时间">
          <template #label>
            <div
              class="w-full flex justify-between"
              v-tippy
              content="延迟开始/列表项逐个延迟的时间"
            >
              <span>延迟时间</span>
              <el-input-number
                v-model="anime.delay"
                size="small"
                :min="0"
                :max="5000"
                class="pure-lack w-20"
                controls-position="right"
              />
            </div>
          </template>
          <el-slider
            v-model="anime.delay"
            class="pl-4 pr-3"
            height="20"
            size="small"
            :min="0"
            :max="5000"
          />
        </el-form-item>
        <el-form-item label="缓动函数">
          <el-select v-model="anime.easing" style="width: 100%;">
            <el-option value="linear" label="linear：线性缓动，动画速度保持恒定。"></el-option>
            <el-option value="easeInQuad" label="easeInQuad：二次方缓动，开始时慢，然后加速。"></el-option>
            <el-option value="easeOutQuad" label="easeOutQuad：二次方缓动，开始时快，然后减速。"></el-option>
            <el-option value="easeInOutQuad" label="easeInOutQuad：二次方缓动，先加速后减速。"></el-option>
            <el-option value="easeInCubic" label="easeInCubic：三次方缓动，开始时慢，然后加速。"></el-option>
            <el-option value="easeOutCubic" label="easeOutCubic：三次方缓动，开始时快，然后减速。"></el-option>
            <el-option value="easeInOutCubic" label="easeInOutCubic：三次方缓动，先加速后减速。"></el-option>
            <el-option value="easeInQuart" label="easeInQuart：四次方缓动，开始时慢，然后加速。"></el-option>
            <el-option value="easeOutQuart" label="easeOutQuart：四次方缓动，开始时快，然后减速。"></el-option>
            <el-option value="easeInOutQuart" label="easeInOutQuart：四次方缓动，先加速后减速。"></el-option>
            <el-option value="easeInQuint" label="easeInQuint：五次方缓动，开始时慢，然后加速。"></el-option>
            <el-option value="easeOutQuint" label="easeOutQuint：五次方缓动，开始时快，然后减速。"></el-option>
            <el-option value="easeInOutQuint" label="easeInOutQuint：五次方缓动，先加速后减速。"></el-option>
            <el-option value="easeInSine" label="easeInSine：正弦缓动，开始时慢，然后加速。"></el-option>
            <el-option value="easeOutSine" label="easeOutSine：正弦缓动，开始时快，然后减速。"></el-option>
            <el-option value="easeInOutSine" label="easeInOutSine：正弦缓动，先加速后减速。"></el-option>
            <el-option value="easeInExpo" label="easeInExpo：指数缓动，开始时慢，然后加速。"></el-option>
            <el-option value="easeOutExpo" label="easeOutExpo：指数缓动，开始时快，然后减速。"></el-option>
            <el-option value="easeInOutExpo" label="easeInOutExpo：指数缓动，先加速后减速。"></el-option>
            <el-option value="easeInCirc" label="easeInCirc：圆形缓动，开始时慢，然后加速。"></el-option>
            <el-option value="easeOutCirc" label="easeOutCirc：圆形缓动，开始时快，然后减速。"></el-option>
            <el-option value="easeInOutCirc" label="easeInOutCirc：圆形缓动，先加速后减速。"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="动画方向">
          <el-radio-group v-model="anime.direction">
            <el-radio label="normal">正常</el-radio>
            <el-radio label="reverse">反向</el-radio>
            <el-radio label="alternate">往返</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="循环播放"><!-- 只能是 true 和 number 不能是 false -->
          <el-switch v-model="anime.loop"></el-switch>
        </el-form-item>

        <el-form-item label="动画属性">
          <el-button
            class="button-new-tag"
            size="small"
            plain
            type="primary"
            @click="handleShowPropWin"
          >
            <template #icon>
              <JIcon :icon="DFT_ICONS.add" />
            </template>
            添加动画属性
          </el-button>
        </el-form-item>

        <div
          v-for="prop in xprops"
          class="anime-selected"
        >
          <div
            class="anime-wrap mini"
            v-if="prop === 'color'"
            v-anime="getAnimeCfgByProp(prop, true)"
          >Color</div>
          <div class="anime-wrap mini" v-else>
            <div class="anime-shadow"></div>
            <div
              class="anime-demo"
              v-anime="getAnimeCfgByProp(prop, true)"
            />
          </div>
          <div class="anime-selected-set">
            <div class="anime-selected-name">{{ prop }}</div>
            <el-input v-model="anime[ prop ]" size="small" class="w-full"></el-input>
            <JIcon
              :icon="DFT_ICONS.delete"
              class="anime-selected-close"
              @click="handleRemoveAnime(prop)"
            />
          </div>
        </div>
      </template>
    </el-form>

    <el-dialog
      v-model="propWin"
      title="选择动画属性"
      width="1080px"
      top="15px"
      custom-class="m-dialog-style"
      :append-to-body="true"
    >
      <!--<h5>CSS TRANSFORMS（优先推荐）</h5>-->
      <el-row v-if="propWin">
        <el-col :span="3" v-for="atf in ANIME_TRANSFORMS">
          <div class="anime-wrap" @click="handleSelectAnime(atf)">
            <div class="anime-shadow"></div>
            <div class="anime-demo" v-anime="getAnimeCfg(atf)"></div>
          </div>
          <div class="anime-name">{{ atf.prop }}: {{ atf.value }}</div>
        </el-col>
      </el-row>

      <!--<h5>CSS PROPERTIES</h5>-->
      <el-row v-if="propWin" style="padding-bottom: 10px;">
        <el-col :span="3" v-for="atf in animeProps">
          <div
            class="anime-wrap"
            v-if="atf.prop === 'color'"
            v-anime="getAnimeCfg(atf)"
            @click="handleSelectAnime(atf)">Color
          </div>
          <div class="anime-wrap" v-else @click="handleSelectAnime(atf)">
            <div class="anime-shadow" v-if="atf.prop !== 'borderRadius'"></div>
            <div class="anime-demo" v-anime="getAnimeCfg(atf)"></div>
          </div>
          <div class="anime-name">{{ atf.prop }}: {{ atf.value }}</div>
        </el-col>
      </el-row>
      <!--<span slot="footer" class="dialog-footer">
          <el-button @click="cancel()">取 消</el-button>
          <el-button type="primary" @click="ok()">确 定</el-button>
      </span>-->
    </el-dialog>
  </div>
</template>

<style lang="scss">
.anime-wrap {
  display: flex;
  justify-content: center;
  align-items: center;
  /*background: #F1F1F1;*/
  width: 120px;
  height: 110px;
  margin: 10px auto 5px;
  position: relative;
  background: rgba(0, 0, 0, .8);
  cursor: pointer;
  color: #FFF;
  transition: all .2s;

  &:hover {
    border: 1px solid #CCC;
    box-shadow: 2px 2px 5px #333;
  }

  .anime-shadow {
    background: #FB89FB;
    width: 40px;
    height: 40px;
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -20px;
    margin-top: -20px;
    opacity: .15;
  }

  .anime-demo {
    width: 40px;
    height: 40px;
    background: #FB89FB;
    z-index: 100;
    position: relative;
    border-width: 2px;
    border-style: solid;
    border-color: #FFF;
    opacity: 1;
  }

  &.mini {
    width: 56px;
    height: 50px;
    margin: 0px;

    .anime-shadow, .anime-demo {
      width: 16px;
      height: 16px;
    }

    .anime-shadow {
      margin-left: -8px;
      margin-top: -8px;
    }

    &:hover {
      border: none;
      box-shadow: none;
    }
  }
}

.anime-name {
  text-align: center;
  font-size: 12px;
  margin-bottom: 5px;
}

h5 {
  text-align: center;
  margin: 5px auto 5px;
}

.anime-selected {
  display: flex;
  background: #FFF;
  margin-bottom: 5px;
  padding: 5px;
  border-radius: 5px;
  position: relative;

  &-set {
    flex: 1;
    padding-left: 10px;
  }

  &-name {
    font-size: 12px;
    font-weight: bold;
    text-align: center;
  }

  &-close {
    position: absolute;
    right: 5px;
    top: 5px;
    /* padding: 5px; */
    width: 18px;
    height: 18px;
    display: flex;
    align-items: center;
    background: rgba(0, 0, 0, .3);
    border-radius: 50%;
    justify-content: center;
    font-size: 12px !important;
    cursor: pointer;

    &:hover {
      color: #FFF;
      background: rgba(0, 0, 0, .8);
    }
  }
}
</style>
